package com.ht.config.quartz;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ht.constant.Enum.JobStatusEnum;
import com.ht.module.job.entity.JobInfo;
import com.ht.module.job.mapper.JobInfoMapper;
import com.ht.module.job.service.JobInfoService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时任务自动配置类
 */
@Slf4j
@Component
public class QuartzJobInitializer implements CommandLineRunner {

    private final JobInfoMapper jobInfoMapper;
    private final JobInfoService jobInfoService;

    public QuartzJobInitializer(JobInfoMapper jobInfoMapper, JobInfoService jobInfoService) {
        this.jobInfoMapper = jobInfoMapper;
        this.jobInfoService = jobInfoService;
    }

    @Override
    public void run(String... args) {
        List<JobInfo> jobs = jobInfoMapper.selectList(
                Wrappers.<JobInfo>lambdaQuery().eq(JobInfo::getStatus, JobStatusEnum.RUNNING)
                        .orderByDesc(JobInfo::getCreateDate)
        );
        for (JobInfo job : jobs) {
            jobInfoService.run(job);
        }
    }
}